package com.logan.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/")
public class FileDownload {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
//	UserService userService;

	@RequestMapping("Download")
	public ModelAndView download(@RequestParam("username") String username,
			@RequestParam("userpwd") String userpwd,
			@RequestParam("filename") String filename,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		
		ModelAndView mv = new ModelAndView();
		
			mv.setViewName("forward:/error.jsp");
//			return mv;
		// --------------------可以直接返回图片 ---------------------------
		// String uri="forward:/upload"+user.getRootpath()+"/"+filename;
		// return uri;
		// ----------------------------------------------------------
		download(request, response, null, filename);
		return null;
	}

	// 文件下载 主要方法
	public void download(HttpServletRequest request,
			HttpServletResponse response, String userPath, String filename)
			throws Exception {

		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String path = request.getSession().getServletContext()
				.getRealPath("upload")
				+ userPath +"/"+ filename;
		File file = new File(path);
		long fileLength = 0;
		// 获取文件的长度
		if (file.exists()) {
			fileLength = file.length();
		} else {
			return;
		}

		// 设置文件输出类型
		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(filename.getBytes("utf-8"), "ISO8859-1"));
		// 设置输出长度
		response.setHeader("Content-Length", String.valueOf(fileLength));
		// 获取输入流
		bis = new BufferedInputStream(new FileInputStream(path));
		// 输出流
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		// 关闭流
		bis.close();
		bos.close();
	}
}
